package com.glodon.paas.framework.registry.core.zk;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class ZooKeeperUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperUtils.class);

    public static ZooKeeper createZooKeeper(final String connectString, int sessionTimeout, final Watcher watcher, int retries) {
        int counter = retries;
        while (counter-- > 0) {
            try {
                return new ZooKeeper(connectString, sessionTimeout, watcher);
            } catch (IOException e) {
                if (counter > 0) {
                    LOGGER.warn("Error connecting to zk cluster, reconnection #{} in 1 second ...", retries - counter);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                        LOGGER.error("Sleeping thread interrupted", e1);
                    }
                } else {
                    LOGGER.error("Error connecting to zk cluster", e);
                    break;
                }
            }
        }
        return null;
    }
}